<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="请输入编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="制单人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="createBy"
            >
              <a-input v-model="model.createBy" placeholder="请输入申请人" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="制单部门"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="createOrgcode"
            >
              <j-select-depart disabled v-model="model.createOrgcode" :multi="false" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="制单日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="createTime"
            >
              <a-input v-model="model.createTime" disabled></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <a-form-model-item
              label="需方单位"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="purchaseCompany"
            >
              <a-input v-model="model.purchaseCompany" placeholder="请输入需方单位"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="发件人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="purchaseBy"
            >
              <a-input v-model="model.purchaseBy" placeholder="请输入发件人"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="传真电话"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="purchasePhone"
            >
              <a-input v-model="model.purchasePhone" placeholder="请输入传真电话"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="采购月份"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="purchaseMonth"
            >
              <j-dict-select-tag
                type="list"
                v-model="model.purchaseMonth"
                dictCode="month"
                placeholder="请输入采购月份"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <a-form-model-item
              label="供方单位"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="supplierName"
            >
              <!-- <erp-goods-supplier
                v-model="model.supplierName"
                placeholder="请输入供方单位"
                @onSuppliersSelected="onSelectSupplier"
                ref="supplierComp"
              >
              </erp-goods-supplier>-->
              <tsl-supplier
                v-model="model.supplierName"
                :isDisabled="formDisabled"
                @handlerOk="onSelectSupplier"
              ></tsl-supplier>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="收件人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="supplierBy"
            >
              <a-input v-model="model.supplierBy" placeholder="请输入收件人"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="传真电话"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="supplierPhone"
            >
              <a-input v-model="model.supplierPhone" placeholder="请输入传真电话"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="交货地点"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="arrivalPlace"
            >
              <a-input v-model="model.arrivalPlace" placeholder="请输入交货地点"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <a-form-model-item
              label="购货名称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="materialName"
            >
              <a-input v-model="model.materialName" placeholder="请输入购货名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="购货数量"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="num"
            >
              <a-input-number v-model="model.num" placeholder="请输入购货数量" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="运输方式"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="transport"
            >
              <j-dict-select-tag
                type="list"
                v-model="model.transport"
                dictCode="transportation_method"
                placeholder="请选择运输方式"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="到货描述"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="arrivalDesc"
            >
              <a-input v-model="model.arrivalDesc" placeholder="请输入到货描述"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <a-form-model-item
              label="付款方式"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="payment"
            >
              <j-dict-select-tag
                type="list"
                v-model="model.payment"
                dictCode="payment_method"
                placeholder="请选择付款方式"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="type">
              <a-input v-model="model.type" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="付款时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="paymentTime"
            >
              <a-input v-model="model.paymentTime" placeholder="请输入付款时间"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="到货日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="arrivalDate"
            >
              <a-input v-model="model.arrivalDate" placeholder="请输入到货日期"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <a-form-model-item
              label="价格基准"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="arrivalPriceType"
            >
              <a-select
                v-model="model.arrivalPriceType"
                :options="priceTypeOption"
                placeholder="请选择价格基准"
              ></a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="价格描述"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="arrivalPrice"
            >
              <a-input v-model="model.arrivalPrice" placeholder="请输入价格描述"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="总价格"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="allPrice"
            >
              <a-input v-model="model.allPrice" placeholder="请输入总价格"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="其他事项" prop="code">
              <a-textarea v-model="model.otherRem" placeholder :rows="4" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <!-- <a-divider style="border-color: #999" dashed /> -->

        <a-row :gutter="16">
          <a-col :span="12">
            <a-card title="供方信息">
              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="供方单位"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierName"
                  >
                    <a-input v-model="model.supplierName"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="地址"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierAddress"
                  >
                    <a-input v-model="model.supplierAddress"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="委托人"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierBy"
                  >
                    <a-input v-model="model.supplierBy"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="传真电话"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierPhone"
                  >
                    <a-input v-model="model.supplierPhone"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="税号"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierTax"
                  >
                    <a-input v-model="model.supplierTax"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="开户银行"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierBank"
                  >
                    <a-input v-model="model.supplierBank"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="账号"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierAccount"
                  >
                    <a-input v-model="model.supplierAccount"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="邮编"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierMail"
                  >
                    <a-input v-model="model.supplierMail"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-card>
          </a-col>
          <a-col :span="12">
            <a-card title="需方信息">
              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="需方单位"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseCompany"
                  >
                    <a-input v-model="model.purchaseCompany"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="地址"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseAddress"
                  >
                    <a-input v-model="model.purchaseAddress"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="委托人"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseBy"
                  >
                    <a-input v-model="model.purchaseBy"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="传真电话"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchasePhone"
                  >
                    <a-input v-model="model.purchasePhone"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="税号"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseTax"
                  >
                    <a-input v-model="model.purchaseTax"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="开户银行"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseBank"
                  >
                    <a-input v-model="model.purchaseBank"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="账号"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseAccount"
                  >
                    <a-input v-model="model.purchaseAccount"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="邮编"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseMail"
                  >
                    <a-input v-model="model.purchaseMail"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-card>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="原料采购订单明细" :key="refKeys[0]" :forceRender="true">
        <a-row justify="start">
          <!-- 新增 -->
          <a-col :span="12">
            <a-space>
              <a-button
                type="primary"
                icon="PlusCircleOutlined"
                size="default"
                @click="addPlan"
                v-show="!formDisabled"
              >追加</a-button>
              <!-- <a-button
                type="primary"
                icon="PlusCircleOutlined"
                size="default"
                @click="addTemporary"
                v-show="!formDisabled || model.procurementType == 0"
              >
                新增
              </a-button>-->
            </a-space>
          </a-col>
          <a-col :span="12"></a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <j-vxe-table
              keep-source
              :ref="refKeys[0]"
              :loading="bussMaterialProcurementDetailTable.loading"
              :columns="bussMaterialProcurementDetailTable.columns"
              :dataSource="bussMaterialProcurementDetailTable.dataSource"
              :maxHeight="300"
              :disabled="formDisabled"
              :rowNumber="false"
              :rowSelection="true"
              class="j-table-force-nowrap1"
              :clickSelectRow="true"
              rowSelectionType="radio"
              @edit-closed="editClosedEvent"
            >
              <template v-slot:action="props">
                <a-popconfirm
                  v-show="!formDisabled"
                  title="确定删除吗？"
                  @confirm="handleDelDetail(props)"
                >
                  <a>删除</a>
                </a-popconfirm>
              </template>
            </j-vxe-table>
          </a-col>
        </a-row>
      </a-tab-pane>
    </a-tabs>
    <plan-modal ref="plan" @ok="handlerok" title="追加计划"></plan-modal>
    <erp-goods-list-model ref="selectGoodsList" category="4" @goodsOk="goodsOk" checkval="radio"></erp-goods-list-model>
    <erp-supplier ref="supplier" @handlerOk="initSupplier"></erp-supplier>
  </a-spin>
</template>

<script>
import ErpGoodsListModel from '@comp/base/modal/ErpGoodsListModal'
import { getAction, httpAction, postAction } from '@/api/manage'
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { validateDuplicateValue } from '@/utils/util'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import ErpSupplier from './ErpSupplierList.vue'
import store from '@/store'
import PlanModal from './BussMaterialProcurementPlanList'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
import moment from 'dayjs'
import ErpGoodsSupplier from '@/components/base/ErpGoodsSupplier'
import GoodsSupplier from '@/components/base/GoodsSupplier'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import TslSupplier from '@comp/tsl/TslSupplier.vue'
import { parseTime } from '@/utils/index.js'
import { definitionStartByDataId, isFirstInitiator } from '@views/flowable/api/definition'

export default {
  name: 'BussMaterialProcurementForm',
  mixins: [JVxeTableModelMixin],
  components: {
    ErpGoodsListModel,
    PlanModal,
    ErpSupplier,
    JSelectDepart,
    ErpGoodsSupplier,
    GoodsSupplier,
    TslSupplier,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      dict: {
        unit: [{ label: '个', value: '1' }],
      },
      priceTypeOption: [
        {
          value: '到库价格',
          label: '到库价格',
        },
        {
          value: '出厂价格',
          label: '出厂价格',
        },
        {
          value: '到港价格',
          label: '到港价格',
        },
      ],
      model: {
        code: '',
        purchaseCompany: '特丝丽化工有限公司',
        purchaseBy: '张业民',
        purchasePhone: '0535-8913021',
        purchaseAddress: '山东省龙口市北马镇北马南路',
        purchaseTax: '91370681613415110K',
        purchaseBank: '中国银行龙口开发区支行',
        purchaseAccount: '226003071547',
        purchaseMail: '265702',
        arrivalPriceType: '到库价格',
        allPrice: '',
        detaillist: [],
        otherRem: '请随车带送货单,化验单',
      },
      supplier: {},
      supplyShow: true,
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        code: [{ required: true, message: '请输入单据编号!' }],
        supplierName: [{ required: true, message: '请输入供方单位!' }],
        purchaseBy: [{ required: true, message: '请填写发件人' }],
        supplierBy: [{ required: true, message: '请填写收件人' }],
        purchaseMonth: [{ required: true, message: '请填写购货月份' }],
        transport: [{ required: true, message: '请选择运输方式' }],
        arrivalPlace: [{ required: true, message: '请填写交货地点' }],
        payment: [{ required: true, message: '请选择付款方式' }],
        paymentTime: [{ required: true, message: '请填写付款时间' }],
        arrivalDate: [{ required: true, message: '请填写到货日期' }],
        num: [
          { required: true, message: '请输入购货数量!' },
          { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!' },
        ],
      },
      refKeys: ['bussMaterialProcurementDetail'],
      tableKeys: ['bussMaterialProcurementDetail'],
      activeKey: 'bussMaterialProcurementDetail',
      // 原料采购订单明细
      bussMaterialProcurementDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '行号',
            key: 'seq',
            type: JVXETypes.normal,
          },
          {
            title: '物料编号',
            key: 'materialCode',
            type: JVXETypes.normal,
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
          },
          {
            title: '名称',
            key: 'materialName',
            type: JVXETypes.normal,
          },
          {
            title: '规格',
            key: 'spec',
            type: JVXETypes.normal,
          },
          {
            title: '单位',
            key: 'unit',
            type: JVXETypes.normal,
          },
          {
            title: '到货日期',
            key: 'arrivalDate',
            type: JVXETypes.input,
          },
          {
            title: '到货价格',
            key: 'procurementArrayPrice',
            type: JVXETypes.inputNumber,
          },
          {
            title: '计划数量',
            key: 'planNum',
            type: JVXETypes.normal,
          },
          {
            title: '已购数量',
            key: 'planGenerateNum',
            type: JVXETypes.normal,
          },
          {
            title: '剩余数量',
            key: 'planLeftNum',
            type: JVXETypes.normal,
          },
          {
            title: '数量',
            key: 'procurementNum',
            type: JVXETypes.inputNumber,
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
          },
          {
            title: '采购计划号',
            key: 'planCode',
            type: JVXETypes.normal,
          },
          {
            title: '计划行号',
            key: 'planSeq',
            type: JVXETypes.normal,
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      url: {
        add: '/business/bussMaterialProcurement/add',
        edit: '/business/bussMaterialProcurement/edit',
        queryById: '/business/bussMaterialProcurement/queryById',
        bussMaterialProcurementDetail: {
          list: '/business/bussMaterialProcurement/queryBussMaterialProcurementDetailByMainId',
        },
        supplierUrl: '/base/erpSupplier/queryById',
        computeUrl: '/business/bussMaterialProcurement/compute/quantity',
      },
      unitDictOptions: {},
      zlunitDictOptions: {},
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    let user = store.getters.userInfo
    if (!this.model.createBy) {
      this.model.createBy = user.username
      this.model.createOrgcode = user.departIds
    }
    this.getPfCode()

    this.initDictConfig()

    //如果是审批流进来的时候要将审批流的数据显示出来
    if (this.customFormData.id != null) {
      this.model = this.customFormData
      //刷新子表数据
      this.editAfter()
    }
  },
  mounted() {},
  methods: {
    getPfCode() {
      postAction('/sys/fillRule/executeRuleByCode/procurement_order_code', {}).then((res) => {
        this.model.code = res.result
      })
    },
    // async getZD(param) {
    //   // 获取数据字典数据
    //   const res = await getAction('/sys/api/queryEnableDictItemsByCode', { code: param })
    //   return res
    // },
    initDictConfig() {
      //初始化字典 - 主单位
      initDictOptions('ji_unit').then((res) => {
        let unitDictOptions = this.unitDictOptions
        if (res.success) {
          res.result.forEach(function (item, index) {
            unitDictOptions[item.value] = item.label
          })
        }
        this.unitDictOptions = unitDictOptions
      })
      //初始化字典 - 辅单位
      initDictOptions('zl_unit').then((res) => {
        let zlunitDictOptions = this.zlunitDictOptions
        console.log(res)
        if (res.success) {
          res.result.forEach(function (item, index) {
            zlunitDictOptions[item.value] = item.label
          })
        }
        this.zlunitDictOptions = zlunitDictOptions
      })
    },
    // editClosedEvent({ row, column }) {
    //   let xTable = this.$refs.xTable
    //   let field = column.property
    //   let cellValue = row[field]
    //   if (row.procurementNum > row.planNum || row.procurementNum + row.generatedNum > row.planNum) {
    //     this.$refs.xTable.revertData(row)
    //     this.$XModal.message({ message: '数量有误，请检查', status: 'warning' })
    //   }
    //   // 判断单元格值是否被修改
    //   if (xTable.isUpdateByRow(row, field)) {
    //     //计算器
    //     // if(row.procurementNum && row.planNum){
    //     this.computeQuity(row).then((res) => {
    //       Object.keys(res.result).forEach((key) => {
    //         this.$set(row, key, res.result[key])
    //       })
    //       this.$refs.xTable.reloadRow(row, null, field)
    //       // this.loading = false
    //     })
    //     // }
    //   }
    // },
    addTemporary() {
      //临时新增
      if (this.model.detaillist && this.model.detaillist.length > 0 && this.model.detaillist[0].planCode) {
        this.$XModal.message({ message: '临时不能与计划混加', status: 'warning' })
        return
      }
      this.$nextTick(() => {
        this.$refs.selectGoodsList.add()
      })
    },
    handlerok(record) {
      if (!record) {
        return
      }
      if (
        this.bussMaterialProcurementDetailTable.dataSource &&
        this.bussMaterialProcurementDetailTable.dataSource.length > 0
      ) {
        let item = this.bussMaterialProcurementDetailTable.dataSource.find(
          (item) => item.procurementPlanId === record.detailId
        )
        if (item) {
          this.$message.warning('该计划单已选择！')
          return
        }
      }
      let isPush = true
      let _this = this
      let detail = {}
      detail.materialName = record.materialName
      detail.materialCode = record.materialCode
      detail.materialId = record.materialId
      detail.planCode = record.code
      detail.procurementNum = record.unPurchaseNum
      detail.procurementArrayPrice = 0
      detail.spec = record.spec
      detail.unit = record.meUnit
      detail.procurementPlanId = record.detailId
      detail.supplierId = record.supplierId
      detail.arrivalDate = record.arrivalDate
      detail.planNum = record.num
      detail.planGenerateNum = record.purchaseNum
      detail.planLeftNum = record.unPurchaseNum
      detail.procurementPlanNo = record.code
      detail.seq = this.bussMaterialProcurementDetailTable.dataSource.length + 1
      detail.planSeq = record.seq
      if (
        this.bussMaterialProcurementDetailTable.dataSource &&
        this.bussMaterialProcurementDetailTable.dataSource > 0
      ) {
        let isPush = this.bussMaterialProcurementDetailTable.dataSource.find(
          (item) => item.procurementPlanId === record.detailId
        )
        if (!isPush) {
          _this.$message.warning('只能选择同一个原料采购计划单')
          return
        }
      }
      if (isPush) {
        this.model.detaillist.push(detail)
        this.bussMaterialProcurementDetailTable.dataSource.push(detail)
        if (this.bussMaterialProcurementDetailTable.dataSource.length > 0) {
          this.loadVendor(this.model.detaillist[0].supplierId)
        }
      }
    },
    addPlan() {
      //追加选择采购计划
      this.$nextTick(() => {
        this.$refs.plan.add()
      })
    },
    goodsOk(record) {
      let detail = {}
      detail.materialName = record.name
      detail.materialCode = record.code
      detail.materialId = record.id
      detail.spec = record.noneSpec
      detail.unit = record.meUnit_dictText
      detail.supplierId = record.supplierId
      this.bussMaterialProcurementDetailTable.dataSource.push(detail)
      this.loadVendor()
    },
    loadVendor() {
      if (this.model.detaillist && this.model.detaillist.length > 0 && this.model.detaillist[0].supplierId) {
        // 加载供应商信息
        getAction('/base/erpSupplier/queryById', { id: this.model.detaillist[0].supplierId }).then((res) => {
          this.supplier = res.result
          this.model.supplierId = this.supplier.id
        })
      }
    },
    showSupplierInfo(supplierId) {
      // 加载供应商信息
      getAction('/base/erpSupplier/queryById', { id: supplierId }).then((res) => {
        this.supplier = res.result
        this.model.supplierId = this.supplier.id
        this.model.supplierName = this.supplier.name
        this.model.supplierAddress = this.supplier.address
        this.model.supplierBy = this.supplier.contact
        this.model.supplierPhone = this.supplier.telephone
        this.model.supplierTax = this.supplier.agent
        this.model.supplierAccount = this.supplier.accountNo
        this.model.supplierBank = this.supplier.bankName
        this.model.supplierMail = this.supplier.email
        //this.$refs.supplierComp.textVals = this.supplier.name
      })
    },
    selectSupplier() {
      //选择供应商
      this.$nextTick(() => {
        this.$refs.supplier.add()
      })
    },
    initSupplier(result) {
      if (this.supplier && this.supplier.id != result.id) {
        this.supplier = {}
        this.model.detaillist = []
      }
      this.supplier = result
      this.model.supplierId = this.supplier.id
    },
    addBefore() {
      this.bussMaterialProcurementDetailTable.dataSource = []
    },
    add() {
      //这里单位字段获取不到怎么解决
      this.bussMaterialProcurementDetailTable.dataSource = []
      let tempList = store.getters.purchasePlanDetailList
      if (tempList.length > 0) {
        let sumNum = 0
        tempList.forEach((row, index) => {
          this.bussMaterialProcurementDetailTable.dataSource.push({
            procurementPlanId: row.detailId,
            planCode: row.code,
            materialId: row.materialId,
            materialCode: row.materialCode,
            materialName: row.materialName,
            spec: row.spec,
            procurementNum: row.unPurchaseNum,
            arrivalDate: row.arrivalDate,
            unit: row.meUnit,
            supplierId: row.supplierId,
            supplierName: row.supplierName,
            //默认价格为零
            procurementArrayPrice: 0,
            planNum: row.num,
            planGenerateNum: row.purchaseNum,
            planLeftNum: row.unPurchaseNum,
            procurementPlanNo: row.code,
            planSeq: row.seq,
            seq: index + 1,
          })

          if (row.num) {
            sumNum += row.num
          }
        })

        //自动计算总量
        this.model.num = sumNum
        this.model.materialName = tempList[0].materialName

        //只有有供应商才加载供应商信息
        if (tempList[0].supplierId) {
          this.showSupplierInfo(tempList[0].supplierId)
        }
      }

      this.model.type = store.getters.purchaseType
    },
    editClosedEvent({ row, column, cellValue }) {
      if (column.property === 'procurementNum' || column.property === 'procurementArrayPrice') {
        //如果输入数量或者价格时自动计算总价格
        if (
          this.bussMaterialProcurementDetailTable.dataSource &&
          this.bussMaterialProcurementDetailTable.dataSource.length > 0
        ) {
          let arr = this.bussMaterialProcurementDetailTable.dataSource
          let price = 0
          let counts = 0
          arr.forEach((element) => {
            console.log(element.procurementNum)
            if (element.procurementNum) {
              counts += element.procurementNum
            }
            if (element.procurementNum && element.procurementArrayPrice) {
              price += element.procurementNum * element.procurementArrayPrice
            }
          })

          if (price > 0) {
            this.model.allPrice = price.toFixed(2)
          }

          if (arr[0].procurementArrayPrice && arr[0].procurementArrayPrice > 0) {
            this.model.arrivalPrice = arr[0].procurementArrayPrice
          }

          if (counts > 0) {
            this.model.num = counts
            this.$forceUpdate()
          }
        }
      }
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter(record) {
      //如果没有明细先要复制一个空数组
      if (!record || record.detaillist == null) {
        this.model.detaillist = []
      }

      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(
          this.url.bussMaterialProcurementDetail.list,
          params,
          this.bussMaterialProcurementDetailTable
        )

        //刷新明细的时候 还要将这个数据传输到要提交的表单中
        if (this.bussMaterialProcurementDetailTable) {
          this.model.detaillist = this.bussMaterialProcurementDetailTable.dataSource
        }
      }

      this.$nextTick(() => {})
    },
    successBack(res) {
      let { result } = res
      this.model = result
      if (this.model.detaillist && this.model.detaillist.length > 0) {
        this.loadVendor()
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_NO_PASSED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              validateError(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        bussMaterialProcurementDetailList: allValues.tablesValue[0].values,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.bussMaterialProcurementDetail.validateTable().then((errMap) => {
        if (errMap) {
          this.$message.error('请检查表单明细内容')
          return
        } else {
          this.$refs.form.validate((valid) => {
            if (valid) {
              that.confirmLoading = true
              let httpurl = ''
              let method = ''
              if (!this.model.id) {
                httpurl += this.url.add
                method = 'post'
              } else {
                httpurl += this.url.edit
                method = 'put'
              }

              if (this.bussMaterialProcurementDetailTable && this.bussMaterialProcurementDetailTable.dataSource) {
                this.model.detaillist = this.bussMaterialProcurementDetailTable.dataSource
                this.model.detaillist.forEach((element) => {
                  element.id = null
                })
              }

              if (!this.model.detaillist || this.model.detaillist.length <= 0) {
                this.$message.warning('没有选择任何物料不能保存')
                that.confirmLoading = false
                return
              }
              console.log(this.model)
              httpAction(httpurl, this.model, method)
                .then((res) => {
                  if (res.success) {
                    //241119修改提交时还要判断是否直接进入审批流
                    if (!this.model.id) {
                      this.model.dataId = res.message
                      that.applySubmit(this.model)
                    }
                    that.$message.success('保存成功')
                    that.$emit('ok')
                  } else {
                    that.$message.warning(res.message)
                  }
                })
                .finally(() => {
                  that.confirmLoading = false
                })
            }
          })
        }
      })
    },
    applySubmit(record) {
      if (record.dataId && record.dataId.length < 1) {
        this.$message.error('审批时必须传入参数dataId')
        return
      }

      //对于自定义业务，判断是否是驳回或退回的第一个发起人节点

      isFirstInitiator(record.dataId, record).then((res) => {
        if (res.success && res.result) {
          // 只有第一次能自动申请
          return
        } else {
          var params = Object.assign(
            {
              dataId: record.dataId,
            },
            record
          )
          //this.queryParams.createTime = parseTime(new Date())
          definitionStartByDataId(record.dataId, 'materialProcurementService', params)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message)

                // todoListNew(this.queryParams).then((response) => {
                //   if (response.success) {
                //     let result = response.result
                //     if (result) {
                //       let records = result.records
                //       if (records) {
                //         if (records[0]) {
                //           this.$message.info('即将跳转到单据审批界面！')
                //           this.$router.push({
                //             path: '/flowable/task/record/index',
                //             query: {
                //               procInsId: records[0].procInsId,
                //               deployId: records[0].deployId,
                //               taskId: records[0].taskId,
                //               businessKey: records[0].businessKey,
                //               nodeType: records[0].nodeType,
                //               category: records[0].category,
                //               finished: true,
                //             },
                //           })
                //         }
                //       }
                //     }
                //   } else {
                //   }
                // })
              } else {
                this.$message.error(res.message)
              }
            })
            .finally()
        }
      })
    },
    onSelectSupplier({ result: record }) {
      this.model.supplierName = record.name
      this.model.supplierId = record.id
      this.model.supplierNo = record.code
      this.model.supplierAddress = record.address
      this.model.supplierBy = record.contact
      this.model.supplierPhone = record.telephone
      this.model.supplierTax = record.fax
      this.model.supplierMail = record.email
      this.model.supplierBank = record.bankName
      this.model.supplierAccount = record.accountNo
      this.model.supplierMail = record.zipCode
      this.$forceUpdate()
    },
    handleDelDetail(props) {
      props.target.removeRows(props.row)
      this.bussMaterialProcurementDetailTable.dataSource.splice(
        this.bussMaterialProcurementDetailTable.dataSource.findIndex((d) => d.id === props.row.id),
        1
      )
    },
    handleOk() {
      //空方法 防止多次提交
    },
  },
}
</script>

<style scoped>
.ant-form-item {
  margin-bottom: 4px;
  margin-left: 4px;
}
</style>
